﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

namespace VDataAdapter
{
    class FirstTimeWorker : Worker
    {
        VdataCommunicator _sender;
        
        DataSource _dataSource;

        public FirstTimeWorker(ManualResetEvent endFirstTime, VdataCommunicator sender, DataSource dataSource)
            : base(null, endFirstTime)
        {
            _sender = sender;
        }

        protected override void DoWork(object data)
        {
            try
            {
                var param = (Dictionary<string, IDictionary<string, PriceLibrary.PriceService.StockBase>>)data;
                var basePrices = (IDictionary<string, PriceLibrary.PriceService.StockBase>)param["BasePrices"];
                var top3Prices = (IDictionary<string, PriceLibrary.PriceService.StockBase>)param["Top3Prices"];

                // update static info first
                UpdateStaticInfo(basePrices, _dataSource);

                _sender.SendFlag(MessageFlagSequeue.BEGIN);

                SendTop3Price(top3Prices, _dataSource, _sender);

                _sender.SendFlag(MessageFlagSequeue.END);

            }
            catch (InvalidCastException ex)
            {
                throw new InvalidCastException("First Time Worker cant convert data " + ex.Message);
            }

            throw new NotImplementedException();
        }

        private void SendTop3Price(IDictionary<string, PriceLibrary.PriceService.StockBase> top3Prices, 
            DataSource dataSource, VdataCommunicator sender)
        {
            foreach (KeyValuePair<string, PriceLibrary.PriceService.StockBase> p in top3Prices)
            {
                var dynamicInfo = (PriceLibrary.PriceService.StockInfoDyns)p.Value;
                
                if (dataSource.BasePrices.ContainsKey(p.Key))
                    sender.SendStock(p.Key, dynamicInfo);
                else
                    throw new KeyNotFoundException("Can find entry" + p.Key + " in Datasource");
            }
        }

        private DataSource UpdateStaticInfo(IDictionary<string, PriceLibrary.PriceService.StockBase> basePrices, DataSource dataSource)
        {
            foreach (KeyValuePair<string, PriceLibrary.PriceService.StockBase> p in basePrices)
            {
                var infoStatic =
                    (PriceLibrary.PriceService.StockInfoStatic)p.Value;
                dataSource.UpdateStockBase(infoStatic);
            }
            return dataSource;
        }
    }
}
